#include "RenderTargetParser.h"
#include "..\utils\Log.h"
#include "..\utils\PlainTextReader.h"
#include "..\base\Engine.h"
#include "..\game\World.h"
#include "..\content\Texture.h"

namespace ds {

void RenderTargetDecl::parseCategory(Category* category) {
	m_Material = category->getProperty("material");
	m_Index = category->read<int>("index",0);
	m_Layers = category->getProperty("layers");
}

bool RenderTargetParser::isSupported(const std::string& fileEnding) const {
	bool ret = false;
	if ( fileEnding == ".rt" ) {
		ret = true;
	}
	return ret;
}

ResourceDeclaration* RenderTargetParser::loadTextFile(const ResourceFile& resourceFile) {
	LOGC(logINFO,"RenderTargetParser") << "Adding render target declaration for file " << resourceFile.fqName;
	PlainTextReader reader;
	if ( reader.readFile(resourceFile.fqName.c_str()) ) {
		Category* root = reader.getRoot();
		RenderTargetDecl* wd = new RenderTargetDecl("RenderTarget");
		wd->parseCategory(root);		
		return wd;
	}
	return 0;
}

void RenderTargetParser::createResource(ResourceDeclaration* declaration) {
	RenderTargetDecl* td = static_cast<RenderTargetDecl*>(declaration);	
	LOGC(logINFO,"RenderTargetParser") << "creating render target " << td->getIndex() << " using material " << td->getMaterial();
	ResourceHandle rh = gEngine->getResourceManager().createRenderTarget(td->getIndex(),td->getMaterial().c_str());
	List<std::string> layers;
	split(td->getLayers(),layers);
	LOGC(logINFO,"RenderTargetParser") << "layers " << td->getLayers();
	for ( uint32 i = 0; i < layers.num();++i ) {
		ds::WorldLayer wl = gEngine->getWorld().getLayerByName(layers[i].c_str());
		gEngine->getRenderer()->assignRenderTarget(rh,wl);	
	}
}

void RenderTargetParser::split(const std::string& str,List<std::string>& words) {
	std::string word;
	std::stringstream stream(str);
	while( getline(stream, word, ',') ) {
		words.append(word);
	}
}

}
